"use strict";
function createCommonjsModule(t, e) {
    return e = {
        exports: {}
    },
    t(e, e.exports),
    e.exports
}
function Backoff(t) {
    t = t || {},
    this.ms = t.min || 100,
    this.max = t.max || 1e4,
    this.factor = t.factor || 2,
    this.jitter = t.jitter > 0 && t.jitter <= 1 ? t.jitter: 0,
    this.attempts = 0
}
function Engine$1(t, e) {
    return this instanceof Engine$1 ? (this.subs = [], t = index$5(t), this.protocol = t.protocol, this.host = t.host, this.query = t.query, this.port = t.port, this.opts = this.opts || {},
    this.path = e.path.replace(/\/$/, ""), this.connected = !1, this.lastPing = null, this.pingInterval = 2e4, void this.bindEvents()) : new Engine$1(t, e)
}
function decodePacket(t) {
    var e = t.charAt(0);
    return t.length > 1 ? {
        type: packetslist[e],
        data: t.substring(1)
    }: {
        type: packetslist[e]
    }
}
function encoder(t, e) {
    var n = encodeAsString(t);
    e([n])
}
function encodeAsString(t) {
    var e = "",
    n = !1;
    return e += t.type,
    t.nsp && "/" != t.nsp && (n = !0, e += t.nsp),
    null != t.id && (n && (e += ",", n = !1), e += t.id),
    null != t.data && (n && (e += ","), e += JSON.stringify(t.data)),
    e
}
function decoder(t, e) {
    var n = void 0;
    "string" == typeof t && (n = decodeString(t)),
    e(n)
}
function decodeString(t) {
    var e = {},
    n = 0;
    if (e.type = Number(t.charAt(0)), null == exports.types[e.type]) return error();
    if ("/" == t.charAt(n + 1)) for (e.nsp = ""; ++n;) {
        var o = t.charAt(n);
        if ("," == o) break;
        if (e.nsp += o, n == t.length) break
    } else e.nsp = "/";
    var i = t.charAt(n + 1);
    if ("" !== i && Number(i) == i) {
        for (e.id = ""; ++n;) {
            var r = t.charAt(n);
            if (null == r || Number(r) != r) {--n;
                break
            }
            if (e.id += t.charAt(n), n == t.length) break
        }
        e.id = Number(e.id)
    }
    if (t.charAt(++n)) try {
        e.data = JSON.parse(t.substr(n))
    } catch(t) {
        return error()
    }
    return e
}
function error(t) {
    return {
        type: exports.ERROR,
        data: "parser error"
    }
}
function Socket$1(t, e) {
    this.io = t,
    this.nsp = e,
    this.id = 0,
    this.connected = !1,
    this.disconnected = !0,
    this.receiveBuffer = [],
    this.sendBuffer = [],
    this.io.autoConnect && this.open()
}
function Manager(t, e) {
    return this instanceof Manager ? (e.path = e.path || "socket.io", this.nsps = {},
    this.subs = [], this.opts = e, this.uri = t, this.readyState = "closed", this.connected = !1, this.reconnection(e.reconnection !== !1), this.reconnectionAttempts(e.reconnectionAttempts || 1 / 0), this.reconnectionDelay(e.reconnectionDelay || 1e3), this.reconnectionDelayMax(e.reconnectionDelayMax || 5e3), this.randomizationFactor(e.randomizationFactor || .5), this.backoff = new index$3({
        min: this.reconnectionDelay(),
        max: this.reconnectionDelayMax(),
        jitter: this.randomizationFactor()
    }), this.timeout(null == e.timeout ? 2e4: e.timeout), this.encoder = encoder, this.decoder = decoder, this.connecting = [], this.autoConnect = e.autoConnect !== !1, void(this.autoConnect && this.open())) : new Manager(t, e)
}
function lookup(t, e) {
    if (!t) throw new Error("uri is required.");
    e = e || {};
    var n = url(t);
    debug("parsed: ", n);
    var o = n.source,
    i = n.id,
    r = n.path,
    s = cache[i] && r in cache[i].nsps,
    c = e.forceNew || e["force new connection"] || !1 === e.multiplex || s;
    debug("cache: ", cache);
    var a = void 0;
    return c ? (debug("newConnection is true"), a = Manager(o, e)) : (debug("newConnection is false"), cache[i] || (debug("----------> no cache"), cache[i] = Manager(o, e)), debug("==========> has cache"), a = cache[i]),
    debug("ready to call io.socket path is -> ", n.path),
    a.socket(n.path)
}
var index$1 = createCommonjsModule(function(t) {
    function e(t) {
        if (t) return n(t)
    }
    function n(t) {
        for (var n in e.prototype) t[n] = e.prototype[n];
        return t
    }
    "undefined" != typeof t && (t.exports = e),
    e.prototype.on = e.prototype.addEventListener = function(t, e) {
        return this._callbacks = this._callbacks || {},
        (this._callbacks["$" + t] = this._callbacks["$" + t] || []).push(e),
        this
    },
    e.prototype.once = function(t, e) {
        function n() {
            this.off(t, n),
            e.apply(this, arguments)
        }
        return n.fn = e,
        this.on(t, n),
        this
    },
    e.prototype.off = e.prototype.removeListener = e.prototype.removeAllListeners = e.prototype.removeEventListener = function(t, e) {
        if (this._callbacks = this._callbacks || {},
        0 == arguments.length) return this._callbacks = {},
        this;
        var n = this._callbacks["$" + t];
        if (!n) return this;
        if (1 == arguments.length) return delete this._callbacks["$" + t],
        this;
        for (var o, i = 0; i < n.length; i++) if (o = n[i], o === e || o.fn === e) {
            n.splice(i, 1);
            break
        }
        return this
    },
    e.prototype.emit = function(t) {
        this._callbacks = this._callbacks || {};
        var e = [].slice.call(arguments, 1),
        n = this._callbacks["$" + t];
        if (n) {
            n = n.slice(0);
            for (var o = 0,
            i = n.length; o < i; ++o) n[o].apply(this, e)
        }
        return this
    },
    e.prototype.listeners = function(t) {
        return this._callbacks = this._callbacks || {},
        this._callbacks["$" + t] || []
    },
    e.prototype.hasListeners = function(t) {
        return !! this.listeners(t).length
    }
}),
slice = [].slice,
index$2 = function(t, e) {
    if ("string" == typeof e && (e = t[e]), "function" != typeof e) throw new Error("bind() requires a function");
    var n = slice.call(arguments, 2);
    return function() {
        return e.apply(t, n.concat(slice.call(arguments)))
    }
},
index$3 = Backoff;
Backoff.prototype.duration = function() {
    var t = this.ms * Math.pow(this.factor, this.attempts++);
    if (this.jitter) {
        var e = Math.random(),
        n = Math.floor(e * this.jitter * t);
        t = 0 == (1 & Math.floor(10 * e)) ? t - n: t + n
    }
    return 0 | Math.min(t, this.max)
},
Backoff.prototype.reset = function() {
    this.attempts = 0
},
Backoff.prototype.setMin = function(t) {
    this.ms = t
},
Backoff.prototype.setMax = function(t) {
    this.max = t
},
Backoff.prototype.setJitter = function(t) {
    this.jitter = t
};
var indexOf = [].indexOf,
index$4 = function(t, e) {
    if (indexOf) return t.indexOf(e);
    for (var n = 0; n < t.length; ++n) if (t[n] === e) return n;
    return - 1
},
on = function(t, e, n) {
    return t.on(e, n),
    {
        destroy: function() {
            t.removeListener(e, n)
        }
    }
},
rvalidchars = /^[\],:{}\s]*$/,
rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,
rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,
rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g,
rtrimLeft = /^\s+/,
rtrimRight = /\s+$/,
parsejson = function(t) {
    return "string" == typeof t && t ? (t = t.replace(rtrimLeft, "").replace(rtrimRight, ""), JSON.parse ? JSON.parse(t) : rvalidchars.test(t.replace(rvalidescape, "@").replace(rvalidtokens, "]").replace(rvalidbraces, "")) ? new Function("return " + t)() : void 0) : null
},
re = /^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,
parts = ["source", "protocol", "authority", "userInfo", "user", "password", "host", "port", "relative", "path", "directory", "file", "query", "anchor"],
index$5 = function(t) {
    var e = t,
    n = t.indexOf("["),
    o = t.indexOf("]");
    n != -1 && o != -1 && (t = t.substring(0, n) + t.substring(n, o).replace(/:/g, ";") + t.substring(o, t.length));
    for (var i = re.exec(t || ""), r = {},
    s = 14; s--;) r[parts[s]] = i[s] || "";
    return n != -1 && o != -1 && (r.source = e, r.host = r.host.substring(1, r.host.length - 1).replace(/;/g, ":"), r.authority = r.authority.replace("[", "").replace("]", "").replace(/;/g, ":"), r.ipv6uri = !0),
    r
},
_debug = function(t) {
    return function() {
        for (var e = arguments.length,
        n = Array(e), o = 0; o < e; o++) n[o] = arguments[o];
        if (__wxConfig.debug) {
            var i; (i = console.log).call.apply(i, [null, t].concat(n))
        }
    }
},
GlobalEmitter = index$1({
    hasEmitte: !1
}),
debug$2 = _debug("app:Engine:");
index$1(Engine$1.prototype);
var packets = {
    open: 0,
    close: 1,
    ping: 2,
    pong: 3,
    message: 4,
    upgrade: 5,
    noop: 6
},
packetslist = Object.keys(packets);
Engine$1.prototype.connect = function() {
    GlobalEmitter.hasEmitte || Engine$1.subEvents();
    var t = this.protocol + "://" + this.host + ":" + this.port + "/" + this.path + "/?" + (this.query ? this.query + "&": "") + "EIO=3&transport=websocket";
    wx.connectSocket({
        url: t
    })
},
Engine$1.prototype.onopen = function() {
    debug$2("on open"),
    this.emit("open")
},
Engine$1.prototype.onclose = function(t) {
    debug$2("on close -> ", t),
    this.destroy(),
    this.emit("close", t)
},
Engine$1.prototype.onerror = function(t) {
    debug$2("on error -> ", t),
    this.emit("error"),
    wx.closeSocket()
},
Engine$1.prototype.onpacket = function(t) {
    switch (debug$2("on packet -> ", t), t.type) {
    case "open":
        this.onHandshake(parsejson(t.data));
        break;
    case "pong":
        this.setPing(),
        this.emit("pong");
        break;
    case "error":
        var e = new Error("server error");
        e.code = t.data,
        this.onerror(e);
        break;
    case "message":
        this.emit("data", t.data),
        this.emit("message", t.data)
    }
},
Engine$1.prototype.onHandshake = function(t) {
    this.id = t.sid,
    this.pingInterval = t.pingInterval,
    this.pingTimeout = t.pingTimeout,
    this.setPing()
},
Engine$1.prototype.setPing = function() {
    var t = this;
    clearTimeout(this.pingIntervalTimer),
    this.pingIntervalTimer = setTimeout(function() {
        t.ping()
    },
    this.pingInterval)
},
Engine$1.prototype.ping = function() {
    debug$2("ping......"),
    this.emit("ping"),
    this._send(packets.ping + "probe")
},
Engine$1.prototype.write = Engine$1.prototype.send = function(t) {
    this._send([packets.message, t].join(""))
},
Engine$1.prototype._send = function(t) {
    debug$2("send message -> ", t),
    wx.sendSocketMessage({
        data: t
    })
},
Engine$1.subEvents = function() {
    wx.onSocketOpen(function() {
        GlobalEmitter.emit("open")
    }),
    wx.onSocketClose(function(t) {
        GlobalEmitter.emit("close", t)
    }),
    wx.onSocketError(function(t) {
        GlobalEmitter.emit("error", t)
    }),
    wx.onSocketMessage(function(t) {
        GlobalEmitter.emit("packet", decodePacket(t.data))
    }),
    GlobalEmitter.hasEmitte = !0
},
Engine$1.prototype.bindEvents = function() {
    this.subs.push(on(GlobalEmitter, "open", index$2(this, "onopen"))),
    this.subs.push(on(GlobalEmitter, "close", index$2(this, "onclose"))),
    this.subs.push(on(GlobalEmitter, "error", index$2(this, "onerror"))),
    this.subs.push(on(GlobalEmitter, "packet", index$2(this, "onpacket"))),
    debug$2("bind events -> ", this.subs)
},
Engine$1.prototype.destroy = function() {
    for (var t = void 0; t = this.subs.shift();) t.destroy();
    clearTimeout(this.pingIntervalTimer),
    this.readyState = "closed",
    this.id = null,
    this.writeBuffer = [],
    this.prevBufferLen = 0,
    debug$2("destroy -> ", this.subs)
},
exports.types = ["CONNECT", "DISCONNECT", "EVENT", "ACK", "ERROR", "BINARY_EVENT", "BINARY_ACK"];
var debug$3 = _debug("app:socket:");
index$1(Socket$1.prototype);
var parser = {
    CONNECT: 0,
    DISCONNECT: 1,
    EVENT: 2,
    ACK: 3,
    ERROR: 4,
    BINARY_EVENT: 5,
    BINARY_ACK: 6
},
events = {
    connect: 1,
    connect_error: 1,
    connect_timeout: 1,
    connecting: 1,
    disconnect: 1,
    error: 1,
    reconnect: 1,
    reconnect_attempt: 1,
    reconnect_failed: 1,
    reconnect_error: 1,
    reconnecting: 1,
    ping: 1,
    pong: 1
},
emit = index$1.prototype.emit;
Socket$1.prototype.subEvents = function() {
    if (!this.subs) {
        var t = this.io;
        this.subs = [on(t, "open", index$2(this, "onopen")), on(t, "packet", index$2(this, "onpacket")), on(t, "close", index$2(this, "onclose"))]
    }
},
Socket$1.prototype.open = Socket$1.prototype.connect = function() {
    return debug$3("socket to open, connected -> ", this.connected),
    this.connected ? this: (this.subEvents(), this.io.open(), "open" == this.io.readyState && this.onopen(), this)
},
Socket$1.prototype.onopen = function() {
    debug$3("on open"),
    "/" != this.nsp && this.packet({
        type: parser.CONNECT
    })
},
Socket$1.prototype.onclose = function(t) {
    debug$3("on close -> ", t),
    this.connected = !1,
    this.disconnected = !0,
    delete this.id,
    this.emit("disconnect", t)
},
Socket$1.prototype.onpacket = function(t) {
    if (t.nsp == this.nsp) switch (t.type) {
    case parser.CONNECT:
        this.onconnect();
        break;
    case parser.EVENT:
        this.onevent(t);
        break;
    case parser.DISCONNECT:
        this.disconnect();
        break;
    case parser.ERROR:
        this.emit("error", t.data)
    }
},
Socket$1.prototype.onconnect = function() {
    debug$3("on connect"),
    this.connected = !0,
    this.disconnected = !1,
    this.emit("connect")
},
Socket$1.prototype.onevent = function(t) {
    var e = t.data || [];
    debug$3("emitting event -> ", t),
    this.connected ? emit.apply(this, e) : this.receiveBuffer.push(e)
},
Socket$1.prototype.close = Socket$1.prototype.disconnect = function() {
    return this.connected && (debug$3("performing disconnect ", this.nsp), this.packet({
        type: parser.DISCONNECT
    })),
    this.destroy(),
    this.connected && this.onclose("io client disconnect"),
    this
},
Socket$1.prototype.destroy = function() {
    if (this.subs) {
        for (var t = 0; t < this.subs.length; t++) this.subs[t].destroy();
        this.subs = null
    }
    this.io.destroy(this)
},
Socket$1.prototype.emit = function() {
    for (var t = arguments.length,
    e = Array(t), n = 0; n < t; n++) e[n] = arguments[n];
    if (events.hasOwnProperty(e[0])) return emit.apply(this, e),
    this;
    var o = parser.EVENT,
    i = {
        type: o,
        data: e,
        options: {}
    };
    return this.connected ? this.packet(i) : this.sendBuffer.push(i),
    this
},
Socket$1.prototype.packet = function(t) {
    t.nsp = this.nsp,
    this.io.packet(t)
};
var debug$1 = _debug("app:Manager:"),
has = Object.prototype.hasOwnProperty;
index$1(Manager.prototype),
Manager.prototype.open = Manager.prototype.connect = function(t) {
    var e = this;
    if (~this.readyState.indexOf("open")) return this;
    this.engine = new Engine$1(this.uri, this.opts),
    this.readyState = "opening";
    var n = this.engine;
    return this.subs.push(on(n, "open",
    function() {
        debug$1("catch open event"),
        e.onopen(),
        t && t()
    })),
    this.subs.push(on(n, "error",
    function(n) {
        if (debug$1("connect_error"), e.cleanup(), e.readyState = "closed", e.emitAll("connect_error", n), t) {
            var o = new Error("Connect error");
            o.data = n,
            t(o)
        } else e.maybeReconnectOnOpen()
    })),
    n.connect(),
    this
},
Manager.prototype.onopen = function() {
    debug$1("on open"),
    this.cleanup(),
    this.readyState = "open",
    this.emit("open");
    var t = this.engine;
    this.subs.push(on(t, "data", index$2(this, "ondata"))),
    this.subs.push(on(t, "ping", index$2(this, "onping"))),
    this.subs.push(on(t, "pong", index$2(this, "onpong"))),
    this.subs.push(on(t, "error", index$2(this, "onerror"))),
    this.subs.push(on(t, "close", index$2(this, "onclose")))
},
Manager.prototype.onclose = function(t) {
    debug$1("on close"),
    this.cleanup(),
    this.readyState = "closed",
    this.emit("close", t),
    debug$1("_reconnection -> ", this._reconnection, "!this.skipReconnect -> ", !this.skipReconnect),
    this._reconnection && !this.skipReconnect && this.reconnect()
},
Manager.prototype.onerror = function(t) {
    debug$1("on error"),
    this.emitAll("error")
},
Manager.prototype.onping = function() {
    this.lastPing = new Date,
    this.emitAll("ping")
},
Manager.prototype.onpong = function() {
    this.emitAll("pong", new Date - this.lastPing)
},
Manager.prototype.ondata = function(t) {
    var e = this;
    debug$1("on data -> ", t),
    this.decoder(t,
    function(t) {
        debug$1("decoding -> ", t),
        e.emit("packet", t)
    })
},
Manager.prototype.packet = function(t) {
    var e = this;
    this.encoder(t,
    function(n) {
        for (var o = 0; o < n.length; o++) e.engine.write(n[o], t.options)
    })
},
Manager.prototype.socket = function(t) {
    debug$1("create socket nsp is -> ", t);
    var e = this.nsps[t];
    return e || (e = new Socket$1(this, t), this.nsps[t] = e),
    e
},
Manager.prototype.cleanup = function() {
    for (var t = void 0; t = this.subs.shift();) t.destroy();
    this.packetBuffer = [],
    this.lastPing = null
},
Manager.prototype.emitAll = function() {
    for (var t = arguments.length,
    e = Array(t), n = 0; n < t; n++) e[n] = arguments[n];
    this.emit.apply(this, e);
    for (var o in this.nsps) has.call(this.nsps, o) && this.nsps[o].emit.apply(this.nsps[o], e)
},
Manager.prototype.reconnect = function() {
    var t = this;
    return debug$1("reconnect: reconnecting -> ", this.reconnecting, "skipReconnect -> ", this.skipReconnect),
    this.reconnecting || this.skipReconnect ? this: void(this.backoff.attempts >= this._reconnectionAttempts ? (debug$1("reconnect failed"), this.backoff.reset(), this.emitAll("reconnect_failed"), this.reconnecting = !1) : !
    function() {
        var e = t.backoff.duration();
        debug$1("will wait %dms before reconnect attempt", e),
        t.reconnecting = !0;
        var n = setTimeout(function() {
            debug$1("attempting reconnect"),
            t.emitAll("reconnect_attempt", t.backoff.attempts),
            t.emitAll("reconnecting", t.backoff.attempts),
            t.skipReconnect || t.open(function(e) {
                e ? (debug$1("reconnect attempt error"), t.reconnecting = !1, t.reconnect(), t.emitAll("reconnect_error", e.data)) : (debug$1("reconnect success"), t.onreconnect())
            })
        },
        e);
        t.subs.push({
            destroy: function() {
                clearTimeout(n)
            }
        })
    } ())
},
Manager.prototype.onreconnect = function() {
    var t = this.backoff.attempts;
    this.reconnecting = !1,
    this.backoff.reset(),
    this.updateSocketIds(),
    this.emitAll("reconnect", t)
},
Manager.prototype.updateSocketIds = function() {
    for (var t in this.nsps) has.call(this.nsps, t) && (this.nsps[t].id = this.engine.id)
},
Manager.prototype.destroy = function(t) {
    var e = index$4(this.connecting, t);~e && this.connecting.splice(e, 1),
    this.connecting.length || this.close()
},
Manager.prototype.close = Manager.prototype.disconnect = function() {
    debug$1("disconnect"),
    this.skipReconnect = !0,
    this.reconnecting = !1,
    "opening" == this.readyState && this.cleanup(),
    this.readyState = "closed",
    this.engine && this.engine.close()
},
Manager.prototype.reconnection = function(t) {
    return arguments.length ? (this._reconnection = !!t, this) : this._reconnection
},
Manager.prototype.reconnectionAttempts = function(t) {
    return arguments.length ? (this._reconnectionAttempts = t, this) : this._reconnectionAttempts
},
Manager.prototype.reconnectionDelay = function(t) {
    return arguments.length ? (this._reconnectionDelay = t, this.backoff && this.backoff.setMin(t), this) : this._reconnectionDelay
},
Manager.prototype.randomizationFactor = function(t) {
    return arguments.length ? (this._randomizationFactor = t, this.backoff && this.backoff.setJitter(t), this) : this._randomizationFactor
},
Manager.prototype.reconnectionDelayMax = function(t) {
    return arguments.length ? (this._reconnectionDelayMax = t, this.backoff && this.backoff.setMax(t), this) : this._reconnectionDelayMax
},
Manager.prototype.timeout = function(t) {
    return arguments.length ? (this._timeout = t, this) : this._timeout
},
Manager.prototype.maybeReconnectOnOpen = function() { ! this.reconnecting && this._reconnection && 0 === this.backoff.attempts && this.reconnect()
};
var url = function(t) {
    var e = index$5(t);
    e.port || (/^(http|ws)$/.test(e.protocol) ? e.port = "80": /^(http|ws)s$/.test(e.protocol) && (e.port = "443")),
    e.path = e.path || "/";
    var n = e.host.indexOf(":") !== -1,
    o = n ? "[" + e.host + "]": e.host;
    return e.id = e.protocol + "://" + o + ":" + e.port,
    e
},
debug = _debug("app:index:"),
cache = {};
module.exports = lookup;